package com.lightjet.macross.base.gateway.service.impl;

import com.lightjet.macross.common.dto.ResponseDTO;
import com.lightjet.macross.common.util.RespUtil;
import javassist.NotFoundException;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

/**
 * @author : lijia
 * @version : 1.0 2020-05-09 12:04
 * description : 动态路由服务实现类
 */
@Service("dynamicRouteService")
@Log
public class DynamicRouteServiceImpl implements ApplicationEventPublisherAware {

    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;
    private ApplicationEventPublisher publisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }


    //增加路由
    public ResponseDTO<String> add(RouteDefinition definition) {
        try
        {
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            notifyChanged();
            return RespUtil.CreateOK("新增路由成功");
        }
        catch (Exception e){
            return RespUtil.CreateError("新增路由【"+definition.getId()+"】失败："+e.getMessage());
        }

    }
    //更新路由
    public ResponseDTO<String> update(RouteDefinition definition) {
        try {
            ResponseDTO<String> res = delete(definition.getId());
            if(res.getResult())
            {
                routeDefinitionWriter.save(Mono.just(definition)).subscribe();
                notifyChanged();
                return RespUtil.CreateOK("更新路由成功");
            }
            else{
                return RespUtil.CreateError("更新路由【"+definition.getId()+"】失败：原路由未找到");
            }
        } catch (Exception e) {
            return RespUtil.CreateError("更新路由【"+definition.getId()+"】失败："+e.getMessage());
        }
    }
    //删除路由
    public ResponseDTO<String> delete(String id) {
        try {
            this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
            notifyChanged();
            return RespUtil.CreateOK("删除路由【"+id+"】成功");
        } catch (Exception e)
        {
            if (e.getCause() instanceof org.springframework.cloud.gateway.support.NotFoundException){
                return RespUtil.CreateError("删除路由【"+id+"】失败：未找到路由");
            }
            else
            {
                return RespUtil.CreateError("删除路由【"+id+"】失败："+ e.getMessage());
            }
        }

    }

    private void notifyChanged() {
        this.publisher.publishEvent(new RefreshRoutesEvent(this));
    }

    /*public Mono<ResponseEntity<Object>> delete(String id) {
        return this.routeDefinitionWriter.delete(Mono.just(id)).then(Mono.defer(() -> {
            return Mono.just(ResponseEntity.ok().build());
        })).onErrorResume((t) -> {
            log.info("未找到ID【"+id+"】的路由");
            return t instanceof NotFoundException;
        }, (t) -> {
            return Mono.just(ResponseEntity.notFound().build());
        });
    }*/
}
